﻿Public Class ReceteKayit : Inherits Process

	Dim eczkod, donem As Input

	Public Overrides Sub GenericEvent(ByVal e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Start("Reçete kaydı", "Eczane ve dönem seçimi yapın.")
				eczkod = AddCombo("eczkod", "Eczane", Saglik.Eczane.EczaneSource, "width=24", "", "Eczane seçimi yapmalısınız.")
				donem = AddDonem("donem", "Dönem", "nl", Today.YM)
				StartBody()
				AddList()
				List.AddButtons("Add.Edit")
				List.AddColumns("receteno(Reçete no.;80c),faturano(Fatura no.;80c)")
				List.AddColumns("sdrm(A/P;40c),kimlik(Kimlik no.;80l),sno(Sigorta no.;80l),adi(Adı;100%l),soyadi(Soyadı;100%l),hturu(Hesap t.;60c),kararno(Karar no.;60r)")
			Case EventType.ValidateForm
				ShowList()
				Help = "Eczanenin ilgili dönemdeki reçeteleri listelenmiştir."
				e.Result = True
			Case EventType.Add
				ShowDialog("add")
		End Select
	End Sub

	Sub ShowList()
		List.DataSource = Saglik.Eczane.ReceteListesi(Remote, eczkod.get, donem.yil, donem.ay)
	End Sub

	Dim WithEvents SumPanel As Panel
	Dim WithEvents Barkod As New BarkodBox

	Public Overrides Sub DialogEvent(e As ProcessEventArgs)
		Select Case e.EventType
			Case EventType.Initialize
				Modal.Start("Reçete kaydı", "Reçete bilgilerini girin.")
				Modal.AddDataWindow("DataWindow", 800, 230)
				Modal.AddList("List", 800, 264)
				Grid = Modal.List
				Grid.AddColumns("*adet(Adet;50c),+ilac(İlaç adı;50%l),etken(Etken madde;50%l),*fiyat(Fiyat;70m),tutar(Tutar;70m)")
				Grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders
				Grid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect
				Barkod.Visible = True
				Barkod.Text = ""
				Modal.Box.ToolStrip.Visible = True
				Modal.Box.Controls.Add(Barkod)
				Barkod.BringToFront()
				Barkod.Location = New Point(1, 1)
				Barkod.Size = New Size(200, 26)
				Barkod.TabIndex = 0
				Grid.TabIndex = 1
				SumPanel = Modal.List.BottomPanel
				SumPanel.Height = 118
				SumPanel.BackColor = Themes.Current.FormColor.Mix(Color.White, 50)
				DataWindow = Modal.DataWindow
			Case EventType.Shown
				Modal.Buttons.Show("Save")
				Rs = Saglik.Recete.Oku(Remote, -1)
				Total = New TotalInfo
				DataWindow.Reset()
				DataWindow.AddGroup("Reçete bilgileri", "receteno;muaynetar;faturano")
				DataWindow.AddGroup("Sigortalı bilgileri", "sdrm;kimlik;sno;adi*;soyadi*;hturu*;kararno*")
				DataWindow.AddGroup("Geçindirmekle yükümlü bilgileri", "ydurum;gyskimlik;gysadi;gyssoyadi")
				DataWindow.Recordset = Rs
				List.Clear()
				For i = 0 To 3
					Modal.List.AddRow()
				Next
				Modal.List.ColumnSource("ilac") = Saglik.Eczane.IlacListesi(Remote)
				Grid.CurrentCell = Nothing
				DataWindow.Fields("sdrm").Value = "A"
				DataWindow.Fields("ydurum").Value = "K"
			Case EventType.Other
				Select Case e.Name
					Case "DataWindow.ydurum.change"
						DataWindow.Fields("gyskimlik").Enabled = DataWindow.Fields("ydurum").Value <> "K"
						DataWindow.Fields("gysadi").Enabled = DataWindow.Fields("ydurum").Value <> "K"
						DataWindow.Fields("gyssoyadi").Enabled = DataWindow.Fields("ydurum").Value <> "K"
				End Select
			Case EventType.Save
				If DataWindow.Check("receteno", DataWindow.Fields("receteno").IsEmpty, "Reçete numarasını girmeniz gerekir.") Then Return
				If DataWindow.Check("receteno", Not Saglik.Eczane.ReceteOku(Remote, DataWindow.Fields("receteno").Value).EOF, "Bu reçete numarası daha önce kullanılmıştır.") Then Return
				If DataWindow.Check("muaynetar", DataWindow.Fields("muaynetar").IsEmpty, "Muayene tarihini girmeniz gerekir.") Then Return
				If DataWindow.Check("faturano", DataWindow.Fields("faturano").IsEmpty, "Fatura numarasını girmeniz gerekir.") Then Return
				If DataWindow.Check("faturano", Not Saglik.Eczane.FaturaOku(Remote, DataWindow.Fields("faturano").Value).EOF, "Bu fatura numarası daha önce kullanılmıştır.") Then Return
				If DataWindow.Check("kimlik", DataWindow.Fields("adi").IsEmpty, "!Hak sahibi bilgisini girmeniz gerekir.") Then Return
				For Each Row In Modal.List.Rows
					If Row.Cells("ilac").Value <> Nothing Then
						If Row.Cells("fiyat").Value = Nothing Then
							Grid.CurrentCell = Row.Cells("fiyat")
							Warning("İlaç fiyatı bilgisinin girilmesi gerekir.")
							Grid.Focus() : Return
						End If
						If Row.Cells("adet").Value = Nothing Then
							Grid.CurrentCell = Row.Cells("adet")
							Warning("İlaç adedi bilgisinin girilmesi gerekir.")
							Grid.Focus() : Return
						End If
					End If
				Next
				If Not Confirm("Reçete kaydedilecek. Girilen bilgileri onaylıyor musunuz?") Then Return
				Try
					Dim recete As New db.saglik.eczane.recete
					recete.eczkod.set(eczkod.get)
					recete.yil.set(donem.yil)
					recete.ay.set(donem.ay)
					recete.import(DataWindow)
					recete.durum.import(DataWindow, "sdrm")
					recete.yadi.import(DataWindow, "gysadi")
					recete.istsekli.set("E")
					recete.ilactopfiat.set(Total.IlacToplami)
					recete.ssd10.set(Total.Indirim)
					recete.sig20.set(Total.Sigortali)
					recete.kdv.set(Total.KDV)
					recete.ssdtopfiat.set(Total.Toplam)
					recete.kaykul.set(User.Kaykul)
					recete.islemtar.set(Remote.SysTime)
					For Each Row In Modal.List.Rows
						If Row.Cells("ilac").Value <> Nothing Then
							Dim ilac As New db.saglik.eczane.recete.ilac
							ilac.faturano.import(DataWindow, "faturano")
							ilac.ilactkod.set(Row.Cells("ilac").Value)
							ilac.adet.set(Row.Cells("adet").Value)
							ilac.fiat.set(Row.Cells("fiyat").Value)
							ilac.toplamfiat.set(Row.Cells("tutar").Value)
							recete.ilaclar.Add(ilac)
						End If
					Next
					recete.save(Remote, False)
					Info("Reçete kaydı tamamlandı.")
					Modal.Reset()
					DataWindow.Fields("receteno").Focus()
				Catch ex As Exception
					Warning("Kayıt sırasında bir hata oluştu.", ex.Message)
				End Try
			Case EventType.Closing
				ShowList()
		End Select
	End Sub

	Shadows WithEvents DataWindow As DataWindow
	Dim WithEvents Grid As Grid

	Private Sub DataWindow_FieldValidating(Control As TextBoxBase, e As System.ComponentModel.CancelEventArgs) Handles DataWindow.FieldValidating
		Select Case Control.Name
			Case "receteno"
				If Not Control.IsDirty Then Return
				e.Cancel = Not Saglik.Eczane.ReceteOku(Remote, Control.Value).EOF
				DataWindow.Check("receteno", e.Cancel, "Bu reçete numarası daha önce kullanılmıştır.")
			Case "faturano"
				If Not Control.IsDirty Then Return
				Dim Rs = Saglik.Eczane.FaturaOku(Remote, Control.Value)
				e.Cancel = Not Rs.EOF
				DataWindow.Check("faturano", e.Cancel, "Bu fatura numarası daha önce kullanılmıştır.")
			Case "kimlik"
				If Not Control.IsDirty Then Return
				If Len(Control.Value) > 0 And Len(Control.Value) < 6 Then
					Control.Value = Trim(Control.Value).PadLeft(6, "0")
				End If
				DataWindow.Fields("adi").Reset()
				DataWindow.Fields("soyadi").Reset()
				DataWindow.Fields("hturu").Reset()
				DataWindow.Fields("kararno").Reset()
				If DataWindow.Fields("kimlik").IsEmpty Then Return
				If DataWindow.Fields("sdrm").Value = "P" Then
					Dim Rs = Emeklilik.KimlikAra(Remote, Modal.DataWindow.Fields("kimlik").Value)
					If Rs.EOF Then Return
					DataWindow.Fields("adi").Value = Rs("adi")
					DataWindow.Fields("soyadi").Value = Rs("soyadi")
					Rs = Rs.Select("odeyerkod < 900")
					If Rs.EOF Then Warning("Bu kişi artık maaş almıyor.") : Return
					DataWindow.Fields("hturu").Value = Rs("hturu")
					DataWindow.Fields("kararno").Value = Rs("kararno")
					DataWindow.Pressed = DataWindow.Fields("gyskimlik")
				Else
					Dim Rs = Sigortali.KimlikAra(Remote, DataWindow.Fields("kimlik").Value)
					If Rs.EOF Then Return
					DataWindow.Fields("sno").Value = Rs("sno")
					DataWindow.Fields("adi").Value = Rs("adi")
					DataWindow.Fields("soyadi").Value = Rs("soyadi")
					DataWindow.Pressed = DataWindow.Fields("gyskimlik")
				End If
			Case "sno"
				DataWindow.Fields("adi").Reset()
				DataWindow.Fields("soyadi").Reset()
				DataWindow.Fields("hturu").Reset()
				DataWindow.Fields("kararno").Reset()
				If DataWindow.Fields("sno").IsEmpty Then Return
				Dim Rs = Sigortali.SnoAra(Remote, DataWindow.Fields("sno").Value)
				If Rs.EOF Then Return
				DataWindow.Fields("kimlik").Value = Rs("kimlik")
				DataWindow.Fields("adi").Value = Rs("adi")
				DataWindow.Fields("soyadi").Value = Rs("soyadi")
		End Select
	End Sub

	Private Sub Grid_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Grid.CellValueChanged
		Static Updating As Boolean = False
		If Updating Then Return
		Updating = True
		Total.IlacToplami = 0
		For Each Row In Modal.List.Rows
			If Row.Cells("adet").Value <> Nothing Then
				Row.Cells("tutar").Value = Row.Cells("adet").Value * Row.Cells("fiyat").Value
				Total.IlacToplami += Row.Cells("tutar").Value
			Else
				Row.Cells("tutar").Value = Nothing
			End If
		Next
		SumPanel.Invalidate()
		Updating = False
	End Sub

	Private Sub Ilac_Propegate(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Grid.Propegate
		e.Handled = True
		Dim Cell = Grid.CurrentCell
		If Not Grid.IsCurrentCellDirty Then
			Select Case Cell.OwningColumn.Name
				Case "adet"
					Grid.EndEdit()
					If Grid.CurrentCell.Value = Nothing Then
						Modal.Buttons.Buttons("Save").Focus()
					Else
						Grid.CurrentCell = Cell.OwningRow.Cells("ilac")
						If Grid.CurrentCell.Value = Nothing Then Grid.BeginEdit(True)
					End If
				Case "ilac"
					If Grid.CurrentCell.Value = Nothing Then
						Grid.CurrentCell = Cell.OwningRow.Cells("adet")
						Grid.CurrentCell.Value = Nothing
					Else
						Grid.CurrentCell = Cell.OwningRow.Cells("fiyat")
					End If
				Case "fiyat"
					If Grid.CurrentRow.Index = Grid.Rows.Count - 1 Then
						Modal.Buttons.Buttons("Save").Focus()
					Else
						Grid.CurrentCell = Grid.Rows(Cell.RowIndex + 1).Cells("adet")
					End If
			End Select
		Else
			Select Case Cell.OwningColumn.Name
				Case "adet"
					Grid.EndEdit()
					If Grid.CurrentCell.Value = Nothing Then
						Modal.Buttons.Buttons("Save").Focus()
					Else
						If Cell.OwningRow.Cells("ilac").Value = Nothing Then
							Grid.CurrentCell = Cell.OwningRow.Cells("ilac")
							Grid.BeginEdit(True)
						Else
							Grid.CurrentCell = Cell.OwningRow.Cells("ilac")
						End If
					End If
				Case "ilac"
					If Grid.EditingControl.Text = "" Then Modal.Buttons.Buttons("Save").Focus() : Return
					Grid.CurrentCell = Cell.OwningRow.Cells("fiyat")
					Grid.CurrentCell.Value = Saglik.Ilac.OkuFiyat(Remote, Cell.Value)
				Case "fiyat"
					If Grid.CurrentRow.Index = Grid.Rows.Count - 1 Then
						Modal.Buttons.Buttons("Save").Focus()
					Else
						Grid.CurrentCell = Grid.Rows(Cell.RowIndex + 1).Cells("adet")
					End If
			End Select
		End If
	End Sub

	Class TotalInfo
		Public IlacToplami As Decimal
		ReadOnly Property Indirim As Decimal
			Get
				Return Math.Round(IlacToplami * 0.075, 2)
			End Get
		End Property
		ReadOnly Property KDV As Decimal
			Get
				Return Math.Round((IlacToplami - Indirim) * 0.05, 2)
			End Get
		End Property
		ReadOnly Property Sigortali As Decimal
			Get
				Return Math.Round((IlacToplami - Indirim + KDV) * 0.2, 2)
			End Get
		End Property
		ReadOnly Property Toplam As Decimal
			Get
				Toplam = Math.Round(IlacToplami - Indirim + KDV - Sigortali, 2)
			End Get
		End Property
	End Class

	Dim Total As TotalInfo

	Private Sub SumPanel_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles SumPanel.Paint
		Dim R1 As New Rectangle(SumPanel.Width - 70, 0, 67, 22)
		Dim R2 As New Rectangle(R1.Left - 500, 0, 500, R1.Height)
		For i = 1 To 5
			Dim acik = Choose(i, "Toplam", "İndirimli (%7.5)", "KDV (%5)", "Sigortalı (%20)", "Ödenecek (%80)")
			Dim v = Choose(i, Total.IlacToplami, Total.Indirim, Total.KDV, Total.Sigortali, Total.Toplam)
			DrawText2(e.Graphics, acik & " :", Font, Color.Black, R2, StrFormat("rm"))
			DrawText2(e.Graphics, Fm(v), Font, Color.Black, R1, StrFormat("rm"))
			R1.Offset(0, R1.Height)
			R2.Offset(0, R2.Height)
		Next
	End Sub

	Private Sub Barkod_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Barkod.Validating
		For Each Row In Modal.List.Rows
			Row.DefaultCellStyle.BackColor = Grid.DefaultCellStyle.BackColor
		Next
		If Barkod.Text = "" Then Return
		If Len(Barkod.Text) > 13 Then Barkod.Text = Mid(Barkod.Text, 4, 13)
		Dim Rs = Saglik.Ilac.BarkodIlac(Remote, Barkod.Text)
		If Rs.EOF Then e.Cancel = True : Warning("Barkod bulunamadı") : Return
		Dim Found As DataGridViewRow = Nothing
		For Each Row In Modal.List.Rows
			If Row.Cells("ilac").Value = Rs("ilactkod") Then
				Found = Row
				Exit For
			ElseIf Row.Cells("ilac").Value = Nothing Then
				Row.Cells("ilac").Value = Rs("ilactkod")
				Row.Cells("etken").Value = Rs("ilacfadi")
				Row.Cells("fiyat").Value = Rs("fiyat")
				Row.Cells("adet").Value = 0
				Found = Row
				Exit For
			End If
		Next
		If Found Is Nothing Then
			Warning("En fazla dört kalem ilaç girilebilir.")
		ElseIf Found.Cells("adet").Value = 2 Then
			Found.DefaultCellStyle.BackColor = If(Found.Cells("adet").Value = 1, Color.FromArgb(192, 255, 0), Color.FromArgb(255, 192, 0))
			Warning("Bir ilaçtan en fazla iki adet girilebilir.")
		ElseIf Found.Cells("adet").Value = 1 AndAlso CStr(Found.Cells("ilac").FormattedValue).EndsWith("**") Then
			Found.DefaultCellStyle.BackColor = If(Found.Cells("adet").Value = 1, Color.FromArgb(192, 255, 0), Color.FromArgb(255, 192, 0))
			Warning("Bu ilaçtan en fazla bir adet girilebilir.")
		Else
			Found.Cells("adet").Value += 1
			Found.DefaultCellStyle.BackColor = If(Found.Cells("adet").Value = 1, Color.FromArgb(192, 255, 0), Color.FromArgb(255, 192, 0))
		End If
		Barkod.Text = ""
		e.Cancel = True
	End Sub

End Class

Class BarkodBox : Inherits TextBox

	Sub New()
		MyBase.new()
		Padding = New Padding(4, 2, 4, 2)
		AllowOnlyNumeric = True
	End Sub

	Public Overrides Property MinimumSize As System.Drawing.Size
		Get
			Return New Size(200, 24)
		End Get
		Set(value As System.Drawing.Size)
		End Set
	End Property

	Public Overrides Property MaximumSize As System.Drawing.Size
		Get
			Return MyBase.MinimumSize
		End Get
		Set(value As System.Drawing.Size)
		End Set
	End Property

	Protected Overrides Sub OnPaintBackground(e As System.Windows.Forms.PaintEventArgs)
		e.Graphics.Clear(Themes.Current.FormColor)
		Dim R = ClientRectangle
		e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
		e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
		e.Graphics.FillRoundRect(R, Color.White.Opacity(If(Focused, 255, 128)).Brush, 4)
		R.Width -= 1 : R.Height -= 1
		e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.None
		e.Graphics.DrawRoundRect(R, Color.Black.Opacity(If(Focused, 128, 64)).Pen, 3)
	End Sub

	Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
		MyBase.OnPaint(e)
		Dim R As New Rectangle(Width - Height, 0, Height, Height)
		R.Inflate(-3, -3)
		e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
		e.Graphics.DrawImage(My.Resources.barcode, R)
	End Sub

	Public Overrides Sub OnDrawCursor(g As System.Drawing.Graphics, x As Integer, R As System.Drawing.Rectangle)
		If Text = "" Then
			R = New Rectangle(0, 0, Height, Height)
			R.Inflate(-4, -4)
			R.Width -= 7
			g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
			g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
			g.FillRoundRect(R, Themes.Current.FormColor.Brush, 2)
		Else
			MyBase.OnDrawCursor(g, x, R)
		End If
	End Sub

	Protected Overrides Sub OnGotFocus(e As System.EventArgs)
		MyBase.OnGotFocus(e)
		DefaultText = "    (Barkodu okutun veya yazın)"
	End Sub

	Protected Overrides Sub OnLostFocus(e As System.EventArgs)
		MyBase.OnLostFocus(e)
		DefaultText = ""
	End Sub

End Class